package com.aiyige.page.edituserinfo;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.User;
import com.aiyige.page.edituserinfo.adapter.EditUserBannerAdapter;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UploadPhotoUtil;
import com.aiyige.utils.banner.BannerAdapter;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;
import timber.log.Timber;

@Route(path = ARouterConfig.EditUserBannerPage)
public class EditUserBannerPage extends AppCompatActivity implements EditBannerBottomDialog.Listener {
    public static final int REQUEST_CODE_ADD_BANNER = 1;
    public static final int REQUEST_CODE_EDIT_BANNER_IMAGE = 2;
    public static final int REQUEST_CODE_ADD_BANNER_URL = 3;
    public static final int REQUEST_CODE_EDIT_BANNER_URL = 4;

    public static final int MAX_BANNER_NUM = 6;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.bannerRv)
    RecyclerView bannerRv;
    EditUserBannerAdapter editUserBannerAdapter;
    EditBannerBottomDialog editBannerBottomDialog;
    int editPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_edit_user_banner);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        titleTv.setText(R.string.manage_banner);
        editBannerBottomDialog = EditBannerBottomDialog.newInstance();
        editBannerBottomDialog.setListener(this);
        bannerRv.setLayoutManager(new GridLayoutManager(this, 2));
        editUserBannerAdapter = new EditUserBannerAdapter();
        editUserBannerAdapter.addData(BannerAdapter.Data.DUMMY_ITEM);
        editUserBannerAdapter.bindToRecyclerView(bannerRv);
        editUserBannerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (editUserBannerAdapter.getItem(position).equals(BannerAdapter.Data.DUMMY_ITEM)) {
                    PictureSelector.create(EditUserBannerPage.this)
                            .openGallery(PictureMimeType.ofImage())
                            .imageSpanCount(4)
                            .selectionMode(PictureConfig.SINGLE)
                            .previewImage(true)
                            .isCamera(true)
                            .enableCrop(true)
                            .sizeMultiplier(0.5f)
                            .withAspectRatio(720, 358)
                            .freeStyleCropEnabled(false)
                            .previewEggs(true)
                            .forResult(REQUEST_CODE_ADD_BANNER);
                } else {
                    editBannerBottomDialog.setPosition(position);
                    editBannerBottomDialog.show(getSupportFragmentManager(), "");
                }
            }
        });
        editUserBannerAdapter.setListener(new EditUserBannerAdapter.Listener() {
            @Override
            public void onPositionChanged() {
                new UpdateUserBannerAsyncTask(EditUserBannerPage.this, editUserBannerAdapter.getData()).execute();
            }
        });
        requestData();
    }

    public void requestData() {
        new RequestUserDataTask().execute();
    }

    public void updateView() {
        if (!ListUtil.isEmpty(AccountUtil.getCurrentUser().getSlideBackup())) {
            List<BannerAdapter.Data> editUserBannerItemList = new LinkedList<>();
            for (User.SlideImage slideImage : AccountUtil.getCurrentUser().getSlideBackup()) {
                BannerAdapter.Data bannerAdapterData = new BannerAdapter.Data();
                bannerAdapterData.setId(slideImage.getId());
                bannerAdapterData.setTitle(slideImage.getTitle());
                bannerAdapterData.setUrl(slideImage.getUrl());
                bannerAdapterData.setLink(slideImage.getRouter());
                bannerAdapterData.setRouter(slideImage.getRouter());
                editUserBannerItemList.add(bannerAdapterData);
            }
            if (editUserBannerItemList.size() < MAX_BANNER_NUM) {
                editUserBannerItemList.add(BannerAdapter.Data.DUMMY_ITEM);
            }
            editUserBannerAdapter.setNewData(editUserBannerItemList);
        }
    }

    @OnClick({R.id.titleBackBtn})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_ADD_BANNER: {
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia item : selectList) {
                        String path;
                        if (item.isCompressed()) {
                            path = item.getCompressPath();
                        } else if (item.isCut()) {
                            path = item.getCutPath();
                        } else {
                            path = item.getPath();
                        }
                        ARouter.getInstance()
                                .build(ARouterConfig.EditBannerUrlPage)
                                .withString("imageUrl", path)
                                .navigation(this, REQUEST_CODE_ADD_BANNER_URL);
                        break;
                    }
                }
                break;
            }

            case REQUEST_CODE_EDIT_BANNER_URL: {
                if (resultCode == RESULT_OK) {
                    BannerAdapter.Data bannerAdapterData = editUserBannerAdapter.getItem(editPosition);
                    bannerAdapterData.setUrl(data.getStringExtra(EditBannerUrlPage.EXTRA_KEY_BANNER_IMAGE_URL));
                    bannerAdapterData.setLink(data.getStringExtra(EditBannerUrlPage.EXTRA_KEY_BANNER_URL));
                    editUserBannerAdapter.setData(editPosition, bannerAdapterData);
                    doPublishBanner();
                }
                break;
            }
            case REQUEST_CODE_ADD_BANNER_URL: {
                if (resultCode == RESULT_OK) {
                    final BannerAdapter.Data bannerAdapterData = new BannerAdapter.Data();
                    bannerAdapterData.setUrl(data.getStringExtra(EditBannerUrlPage.EXTRA_KEY_BANNER_IMAGE_URL));
                    bannerAdapterData.setLink(data.getStringExtra(EditBannerUrlPage.EXTRA_KEY_BANNER_URL));
                    editUserBannerAdapter.addData(editUserBannerAdapter.getItemCount() - 1, bannerAdapterData);
                    if (editUserBannerAdapter.getItemCount() > MAX_BANNER_NUM) {
                        editUserBannerAdapter.remove(editUserBannerAdapter.getItemCount() - 1);
                    }
                    UploadPhotoUtil.newBuilder()
                            .listener(new UploadPhotoUtil.Listener() {
                                LoadingDialog loadingDialog;

                                @Override
                                public void onPreUpload() {
                                    loadingDialog = LoadingDialog.newBuilder()
                                            .with(EditUserBannerPage.this)
                                            .message(R.string.uploading)
                                            .show();
                                }

                                @Override
                                public void onProgress(double progress) {
                                    Timber.e("onProgress:" + progress);
                                }

                                @Override
                                public void onFail(Throwable t) {
                                    loadingDialog.dismiss();
                                    ToastX.show(t.getMessage());
                                }

                                @Override
                                public void onFinish(String url) {
                                    bannerAdapterData.setUrl(url);
                                    loadingDialog.dismiss();
                                    doPublishBanner();
                                }
                            }).photoLocalUrl(bannerAdapterData.getUrl())
                            .build()
                            .upload();
                }
                break;
            }

            case REQUEST_CODE_EDIT_BANNER_IMAGE: {
                if (resultCode == RESULT_OK) {
                    final BannerAdapter.Data bannerAdapterData = editUserBannerAdapter.getItem(editPosition);
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (ListUtil.isEmpty(selectList)) {
                        break;
                    }
                    String path;
                    LocalMedia localMedia = selectList.get(0);
                    if (localMedia.isCompressed()) {
                        path = localMedia.getCompressPath();
                    } else if (localMedia.isCut()) {
                        path = localMedia.getCutPath();
                    } else {
                        path = localMedia.getPath();
                    }
                    bannerAdapterData.setUrl(path);
                    editUserBannerAdapter.setData(editPosition, bannerAdapterData);
                    UploadPhotoUtil.newBuilder()
                            .listener(new UploadPhotoUtil.Listener() {
                                LoadingDialog loadingDialog;

                                @Override
                                public void onPreUpload() {
                                    loadingDialog = LoadingDialog.newBuilder()
                                            .with(EditUserBannerPage.this)
                                            .message(R.string.uploading)
                                            .show();
                                }

                                @Override
                                public void onProgress(double progress) {
                                    Timber.e("onProgress:" + progress);
                                }

                                @Override
                                public void onFail(Throwable t) {
                                    loadingDialog.dismiss();
                                    ToastX.show(t.getMessage());
                                }

                                @Override
                                public void onFinish(String url) {
                                    bannerAdapterData.setUrl(url);
                                    loadingDialog.dismiss();
                                    doPublishBanner();
                                }
                            }).photoLocalUrl(path)
                            .build()
                            .upload();
                }
            }
            default: {
                super.onActivityResult(requestCode, resultCode, data);
                break;
            }
        }
    }

    @Override
    public void editPhoto(int position) {
        editPosition = position;
        PictureSelector.create(EditUserBannerPage.this)
                .openGallery(PictureMimeType.ofImage())
                .imageSpanCount(4)
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(true)
                .isCamera(true)
                .enableCrop(true)
                .sizeMultiplier(0.5f)
                .withAspectRatio(720, 358)
                .freeStyleCropEnabled(false)
                .previewEggs(true)
                .forResult(REQUEST_CODE_EDIT_BANNER_IMAGE);
    }

    @Override
    public void editUrl(int position) {
        editPosition = position;
        ARouter.getInstance().build(ARouterConfig.EditBannerUrlPage)
                .withString("imageUrl", editUserBannerAdapter.getItem(position).getUrl())
                .withString("bannerUrl", editUserBannerAdapter.getItem(position).getLink())
                .navigation(this, REQUEST_CODE_EDIT_BANNER_URL);
    }

    @Override
    public void delete(int position) {
        if (editUserBannerAdapter.getItemCount() == MAX_BANNER_NUM && editUserBannerAdapter.getItem(editUserBannerAdapter.getItemCount() - 1) != BannerAdapter.Data.DUMMY_ITEM) {
            editUserBannerAdapter.remove(position);
            editUserBannerAdapter.addData(BannerAdapter.Data.DUMMY_ITEM);
        } else {
            editUserBannerAdapter.remove(position);
        }
        doPublishBanner();
    }

    public void doPublishBanner() {
        List<User.SlideImage> slideImageList = new LinkedList<>();
        for (BannerAdapter.Data item : editUserBannerAdapter.getData()) {
            if (item == BannerAdapter.Data.DUMMY_ITEM) continue;
            slideImageList.add(User.SlideImage.newBuilder()
                    .url(item.getUrl())
                    .router(item.getLink())
                    .title(item.getTitle())
                    .build());
        }
        new AsyncTask<Object, Object, Object>() {
            //LoadingDialog loadingDialog;


            @Override
            protected void onPreExecute() {
//                loadingDialog = LoadingDialog.newBuilder()
//                        .with(EditUserBannerPage.this)
//                        .message(R.string.uploading)
//                        .show();
            }

            @Override
            protected Object doInBackground(Object... objects) {
                try {
                    Response<ResponseBody> response = ApiManager.getService()
                            .userCenterUsers(AccountUtil.getCurrentUser().getId(), User.newBuilder().slideBackup((List<User.SlideImage>) objects[0]).build())
                            .execute();
                    if (response.code() != ResponseCode.CREATED) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    User tempUser = JSON.parseObject(json, User.class);
                    User user = AccountUtil.getCurrentUser();
                    user.setSlideBackup(tempUser.getSlideBackup());
                    AccountUtil.updateCurrentUser(user);
                    return null;
                } catch (Exception e) {
                    return e;
                }
            }

            @Override
            protected void onPostExecute(Object o) {
//                loadingDialog.dismiss();
                if (o instanceof Exception) {
                    ToastX.show(((Exception) o).getMessage());
                } else {
                    ToastX.show(R.string.edit_user_banner_success);
                }
            }
        }.execute(slideImageList);
    }

    private class RequestUserDataTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(EditUserBannerPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                if (AccountUtil.isLogin()) {
                    Response<ResponseBody> response = ApiManager.getService()
                            .userCenterUsers(AccountUtil.getCurrentUser().getId())
                            .execute();
                    if (response.code() != ResponseCode.OK) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    String json = response.body().string();
                    User tempUser = JSON.parseObject(json, User.class);
                    User user = AccountUtil.getCurrentUser();
                    user.update(tempUser);
                    AccountUtil.updateCurrentUser(user);
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                updateView();
            }
        }
    }

    public class UpdateUserBannerAsyncTask extends SafeAsyncTask<Object, Object, Object> {
        List<User.SlideImage> slideImageList = new LinkedList<>();

        public UpdateUserBannerAsyncTask(Activity activity, List<BannerAdapter.Data> data) {
            super(activity, R.string.text_process);
            for (BannerAdapter.Data item : data) {
                if (item == BannerAdapter.Data.DUMMY_ITEM) continue;
                slideImageList.add(User.SlideImage.newBuilder()
                        .url(item.getUrl())
                        .router(item.getLink())
                        .title(item.getTitle())
                        .build());
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .userCenterUsers(AccountUtil.getCurrentUser().getId(), User.newBuilder().slideBackup(slideImageList).build())
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                User tempUser = JSON.parseObject(json, User.class);
                User user = AccountUtil.getCurrentUser();
                user.setSlideBackup(tempUser.getSlideBackup());
                AccountUtil.updateCurrentUser(user);
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            }
        }
    }

}
